﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using com.hyrentals.common;
using com.hyrentals.webcommon.api;
using com.hyrentals.webcommon.filter;

namespace com.hyrentals.webcommon.extensions
{
    public static class ControllerExtensions
    {
        public static ActionResult JsonSuccess(this ControllerBase ctrl,
            object content,
            JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet,
            string contentType = null,
            Encoding contentEncoding = null)
        {
            var data = new JsonResultObj
            {
                Result = ResultStatusCode.Success,
                Content = content,
            };

            var result = new JsonResult
            {
                ContentEncoding = contentEncoding,
                ContentType = contentType,
                Data = data,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            };

            return result;
        }

        private static ComponentType GetComponentType(ControllerBase ctrl)
        {
            var filter = ctrl.GetType().GetCustomAttribute<OnErrorAttribute>();
            if (filter != null)
            {
                return filter.ComponentType;
            }

            return ComponentType.Unknown;
        }

        public static ActionResult JsonFail(this ControllerBase ctrl,
            uint errorId,
            string errorMsg,
            JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet,
            string contentType = null,
            Encoding contentEncoding = null)
        {
            var module = GetComponentType(ctrl);

            var data = new JsonResultObj
            {
                Result = ResultStatusCode.Error,
                Content = new ErrorData
                {
                    ComponentType = module,
                    ErrorId = errorId,
                    ErrorMsg = errorMsg,
                },
            };

            JavaScriptSerializer jss = new JavaScriptSerializer();
            Logger.Error(jss.Serialize(data));

            var result = new JsonResult
            {
                ContentEncoding = contentEncoding,
                ContentType = contentType,
                Data = data,
                JsonRequestBehavior = behavior,
            };

            return result;
        }

        public static ActionResult JsonFail(this ControllerBase ctrl,
            CommonErrorId errorId,
            string errorMsg,
            JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet,
            string contentType = null,
            Encoding contentEncoding = null)
        {
            return ctrl.JsonFail((uint)errorId, errorMsg,
                behavior, contentType, contentEncoding);
        }
    }
}
